/**
 * Program  : EvacuationMapTask.java
 * Author   : long
 * Create   : 2016年5月14日 下午3:11:21
 *
 * Copyright 2016 by Embedded Internet Solutions Inc.,
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Embedded Internet Solutions Inc.("Confidential Information").  
 * You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement 
 * you entered into with Embedded Internet Solutions Inc.
 *
 */
	
package cn.broadin.app.hotel.task;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import cn.broadin.app.hotel.dialog.DownLoadDialog;
import cn.broadin.app.hotel.util.XLog;
import cn.broadin.app.hotel.util.XToast;
import cn.broadin.app.hotel.util.XUIHelper;

/**
 * 
 * 下载疏散图线程
 * 
 * @author   long
 * @version  1.0.0
 * @date 2016年5月14日下午3:11:21
 */
public class EvacuationMapTask extends AsyncTask<String[], String, Void>{

	private static final String TAG = "EvacuationMapTask";
	private Activity mActivity;
	private Handler handler = null;
	private boolean isStop = false;
	
	private DownLoadDialog mDownLoadDialog;
	private AddListener mAddListener;
	
	@SuppressLint("HandlerLeak")
	public EvacuationMapTask(Activity activity, AddListener addListener) {
		XLog.i(TAG, "EvacuationMapTask start.");
		this.mActivity = activity;
		mDownLoadDialog = new DownLoadDialog(activity);
		this.mAddListener = addListener;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		handler = new Handler(){
			public void handleMessage(Message msg){
				switch (msg.what) {
				case -1:
					long maxLen = Long.parseLong(msg.obj.toString());
					mDownLoadDialog.setMax((int)maxLen);
					break;
				case 0:
					mDownLoadDialog.setProgress(msg.arg1);
					break;
				case 1:
					mAddListener.onSuccess();
					break;
				case 2:
					mDownLoadDialog.dismiss();
					XToast.makeText(mActivity, "文件下载失败", 5000).show();
					break;
				default:
					break;
				}
			}
		};
		mDownLoadDialog.show();
	}

	@Override
	protected Void doInBackground(String[]... params) {
		XLog.i(TAG, "path: " + params[0][0]+";name="+params[0][1]);
		downAppFile(params[0][0], params[0][1], params[0][2], handler,  mActivity);
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		mDownLoadDialog.dismiss();
	}
	
	public void downAppFile(String downPath, String saveDir, String fileName, Handler handler, Activity ctx) {
		XLog.i(TAG, "downAppFile path : " + downPath);
		Message msg = null;
		try {
			URL url = new URL(downPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			long length = conn.getContentLength();
			msg = handler.obtainMessage();
			msg.what = -1;
			msg.obj = length;
			handler.sendMessage(msg);
			XLog.i(TAG, "downAppFile size is : " + length);
			InputStream is = conn.getInputStream();
			FileOutputStream fileOutputStream = null;
			if (is == null) {
				msg = handler.obtainMessage();
				msg.what = 2;
				handler.sendMessage(msg);
				XLog.e(TAG, "downAppFile error. InputStream is null!");
				return;
			}
			File file = new File(saveDir, fileName);
			fileOutputStream = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buf = new byte[1024];
			int ch = -1;
			int total = 0;
			do {
				if(isStop){
					break;
				}
				ch = bis.read(buf);
				if (ch <= 0)
					break;
				fileOutputStream.write(buf, 0, ch);
				total += ch;
				msg = handler.obtainMessage();
				msg.what = 0;
				msg.arg1 = total;
				handler.sendMessage(msg);
			} while (true);
			
			if(!isStop){
				msg = handler.obtainMessage();
				msg.what = 1;
				handler.sendMessage(msg);
				
				conn.disconnect();
				fileOutputStream.close();
				bis.close();
				is.close();
			}
		} catch (MalformedURLException e) {
			msg = handler.obtainMessage();
			msg.what = 2;
			handler.sendMessage(msg);
			XLog.e(TAG, "downAppFile error." + e.getMessage());
		} catch (FileNotFoundException e) {
			msg = handler.obtainMessage();
			msg.what = 2;
			handler.sendMessage(msg);
			XLog.e(TAG, "downAppFile error." + e.getMessage());
		} catch (IOException e) {
			msg = handler.obtainMessage();
			msg.what = 2;
			handler.sendMessage(msg);
			XLog.e(TAG, "downAppFile error. " + e.getMessage());
		}
	}
	
	public static interface AddListener{
		public void onSuccess();
	}
}

